//
//  BOCProgressHandler.m
//  ScrollView无限轮播
//
//  Created by LeungChaos on 16/5/4.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "BOCProgressHandler.h"
#import "BOCNetworkImageManager.h"

#define BOCProgressHandlerMadeKeyPath(key) NSStringFromSelector(@selector(key))

@interface BOCProgressHandler ()
/**
 *  下载进度模型
 */
@property (nonatomic, strong) NSProgress *progressModel;
/**
 *  引用下载任务
 */
@property (nonatomic, weak) NSURLSessionTask *task;
/**
 *  回调下载进度
 */
@property (nonatomic, copy) BOCProgressHandlerProgressBlock progressBlock;

@end

@implementation BOCProgressHandler

/*
 这个类的作用是:
 1.监听下载进度
 2.对监听到的数据通过block进行回调
 */
+ (instancetype)progressHandlerWithProgressBlock:( BOCProgressHandlerProgressBlock __nonnull )progressBlock task:( NSURLSessionTask * __nonnull )task
{
    return [[self alloc]initWithProgressBlock:progressBlock task:task];
}

- (instancetype)initWithProgressBlock:(BOCProgressHandlerProgressBlock __nonnull )progressBlock task:( NSURLSessionTask * __nonnull )task
{
    self = [super init];
    if (self) {
        // 接收下载任务完成时的通知
//        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeObservers) name:BOCDownloadCompletedNotification object:nil];
        
        if (task) {
            self.task = task;
            if (progressBlock) {
                self.progressBlock = progressBlock;
                self.progressModel = [NSProgress progressWithTotalUnitCount:task.countOfBytesExpectedToReceive];
            }
        }
    }
    return self;
}

- (void)setTask:(NSURLSessionTask *)task
{
    _task = task;
    [task addObserver:self
           forKeyPath:BOCProgressHandlerMadeKeyPath(countOfBytesReceived)
              options:NSKeyValueObservingOptionNew
              context:NULL];
    [task addObserver:self
           forKeyPath:BOCProgressHandlerMadeKeyPath(countOfBytesExpectedToReceive)
              options:NSKeyValueObservingOptionNew
              context:NULL];
}

- (void)setProgressModel:(NSProgress *)progressModel
{
    _progressModel = progressModel;
    [progressModel addObserver:self
           forKeyPath:BOCProgressHandlerMadeKeyPath(totalUnitCount)
              options:NSKeyValueObservingOptionNew
              context:NULL];
    [progressModel addObserver:self
           forKeyPath:BOCProgressHandlerMadeKeyPath(completedUnitCount)
              options:NSKeyValueObservingOptionNew
              context:NULL];
}

- (void)removeObservers
{
    [self.task removeObserver:self
                   forKeyPath:BOCProgressHandlerMadeKeyPath(countOfBytesReceived)];
    [self.task removeObserver:self
                   forKeyPath:BOCProgressHandlerMadeKeyPath(countOfBytesExpectedToReceive)];
    [self.progressModel removeObserver:self
                            forKeyPath:BOCProgressHandlerMadeKeyPath(totalUnitCount)];
    [self.progressModel removeObserver:self
                            forKeyPath:BOCProgressHandlerMadeKeyPath(completedUnitCount)];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([object isKindOfClass:[NSURLSessionTask class]]) {
        if ([keyPath isEqualToString:BOCProgressHandlerMadeKeyPath(countOfBytesReceived)]) {
            self.progressModel.completedUnitCount = [(NSNumber *)change[NSKeyValueChangeNewKey] longLongValue];
        }
        if ([keyPath isEqualToString:BOCProgressHandlerMadeKeyPath(countOfBytesExpectedToReceive)]) {
            self.progressModel.totalUnitCount = [(NSNumber *)change[NSKeyValueChangeNewKey] longLongValue];
        }
    }
    if ([object isEqual:self.progressModel]) {
        if (self.progressBlock) {
            dispatch_mainQueue_safely_sync(^{
                self.progressBlock(self.progressModel);
            });
        }
    }
}

- (void)dealloc
{
    BOCLog(@"%s",__func__);
}

@end
